
export default{
  
  //开启命名空间
  namespaced:true,
  
  //()=>({})等同于()=>{return {}}  防止数据被多次使用时进行污染
  //state:{}
  state:()=>({
    carlist:JSON.parse(uni.getStorageSync('carlist') || '[]'),//存储购物车数据
  }),
  
  
  mutations:{
    
    getcarData(state,goods){
       // 购物车的数组，用来存储购物车中每个商品的信息对象
      // 每个商品的信息对象，都包含如下 6 个属性：
     // { goods_id, goods_name, goods_price, goods_count, goods_small_logo, goods_state }
     const findId = state.carlist.find((x)=>x.goods_id===goods.goods_id)
      if(findId){
        findId.goods_count++
      }else{
        state.carlist.push(goods);
      }
      // 通过 commit 方法，调用 m_cart 命名空间下的 storageData 方法
      this.commit('my_car/storageData')
    },
    
    /*存储化数据*/
    storageData(state){
      uni.setStorageSync('carlist',JSON.stringify(state.carlist))
    },
    
    /*管理商品的选中状态*/
    checkStatus(state,goods){
      const finState = state.carlist.find(x=>x.goods_id === goods.goods_id)      
      if(finState){
        finState.goods_state =  goods.goods_state
      }
      this.commit('my_car/storageData')
    },
    
    /*管理商品数量*/
    changeNum(state,goods){
      const finCount = state.carlist.find(x=>x.goods_id === goods.goods_id)
      if(finCount){
        finCount.goods_count = goods.goods_count
        this.commit('my_car/storageData')
      }      
    },
    
    /*删除购物车商品*/
    removeGods(state,goods){
     state.carlist = state.carlist.filter(x=>x.goods_id != goods.goods_id) 
     this.commit('my_car/storageData')
    },
    
    
    /*商品全选*/
    checkGods(state,goods){
      goods.forEach(x=>{
        if(x.goods_state==false){
          x.goods_state = !x.goods_state
        }
      })
    },
    
    /*商品全不选*/
    notCkGods(state,goods){
      goods.forEach(x=>{x.goods_state = !x.goods_state})
    },
    
    
    
  },
  
  
  getters:{
    /*购物车总数*/
    total(state){
      let c = state.carlist.length
      return c
    },
    
    /*结算数量*/
    payNum(state){
      //reduce()累加函数
      return state.carlist.filter(x=>x.goods_state).reduce(
      (total,item)=> total+=item.goods_count,0
      )
    },
    
    /*结算总金额*/
    checkedGoodsAmount(state){
      //使用 reduce 方法，将已勾选的商品数量 * 单价之后，进行累加
      return state.carlist.filter(x=>x.goods_state).reduce(
      (p,item)=> p +=item.goods_count * item.goods_price,0
      ).toFixed(2)
    }
    
  }
  
  
}